﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace CRM.Models
{
    public class Menu : BaseModel
    {
        public Menu() { }
        public Menu(string ModuleEnumTypeName,Enum PermissionFlag) {
            Module = ModuleEnumTypeName;
            this.PermissionFlag = Convert.ToInt64(PermissionFlag);
        }
        public int Id { get; set; }

        [Column(TypeName = "varchar(50)")]
        public string Module { get; set; }
        public long PermissionFlag { get; set; }
        [Column(TypeName = "varchar(255)")]
        public string Path { get; set; }

        [Column(TypeName = "varchar(50)")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
        public string Redirect { get; set; }

        [Column(TypeName = "varchar(255)")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
        public string Component { get; set; }

        [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
        [Column(TypeName = "json")]
        public string MetaJson { get; set; }

        [Column(TypeName = "varchar(50)"), Comment("介绍，描述")]
        public string Desc { get; set; } = null;
        [Column("sort", TypeName = "int(11)"), Comment("排序字段 从小到大")]
        public long Sort { get; set; } = 0;
        [NotMapped]
        public bool Has { get; set; } = false;

        [NotMapped]
        public MetaSt Meta
        {
            get {
                var json = JsonSerializer.Deserialize<MetaSt>(MetaJson);
                json.AlwaysShow = ParentId == null;
                return json;
            }
            set => MetaJson = JsonSerializer.Serialize(value);
        }

        public int? ParentId { get; set; }

        [Newtonsoft.Json.JsonIgnore]
        public Menu Parent { get; set; }

        [InverseProperty(nameof(Parent))]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
        public List<Menu> Children { get; set; }

        [Column(TypeName = "varchar(50)")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
        public string Name { get; set; }
        public static async Task<List<Menu>> GetUiRoutesListAsync(DbSet<Menu> menus)
        {
            return await menus.Where(m => m.ParentId == null).OrderBy(i => i.Sort).Include(m => m.Children.OrderBy(i => i.Sort)).ToListAsync();
        }
    }
}
